#!/sbin/openrc-run

name=lotide
description="Lotide Backend"

extra_stopped_commands="setup migrate"
description_setup="Setup the Lotide database"
description_migrate="Run Lotide database migrations"

export DATABASE_URL
export LOTIDE_PORT
export HOST_URL_ACTIVITYPUB
export HOST_URL_API
export APUB_PROXY_REWRITES
export ALLOW_FORWARDED
export SMTP_URL
export SMTP_FROM
export MEDIA_LOCATION

command="/usr/bin/lotide"
command_background=true
command_user="lotide:lotide"
pidfile="/run/${RC_SVCNAME}.pid"
error_log="/var/log/lotide.log"

depend() {
	need localmount net
	after firewall postgresql
}

start_pre() {
	checkpath -f -m 0640 -o "$command_user" "$error_log"
	checkpath -d -m 0750 -o "$command_user" "/var/lib/lotide"

	lotide_exec migrate
}

setup() {
	local dbname dbuser dbpass domain sqlhost sqlport sqluri
	local sqlfile="$(mktemp -u).sql"

	read -p "Lotide db name: " dbname
	read -p "Lotide db user: " dbuser
	read -p "Lotide db password: " dbpass
	read -p "Lotide domain: " domain
	read -p "PostgreSQL host: " sqlhost
	read -p "PostgreSQL port: " sqlport

	sqluri="\"postgres:\/\/$dbuser:$dbpass@$sqlhost:$sqlport\/$dbname\""

	sed -i -e "s/lotide\.example\.com/$domain/g" \
		-e "/^DATABASE_URL/s/=.*/=$sqluri/" \
		/etc/conf.d/lotide

	if [ -f /etc/conf.d/hitide ]; then
		sed -i -e "s/lotide\.example\.com/$domain/g" \
			/etc/conf.d/hitide
	fi

	umask 0177
	cat > "$sqlfile" <<-EOF
		CREATE USER $dbuser WITH PASSWORD '$dbpass';
		CREATE DATABASE $dbname OWNER $dbuser;
	EOF

	einfo "Initialize your Lotide db with $sqlfile,"
	einfo "then run: rc-service $RC_SVCNAME migrate"
}

migrate() {
	ebegin "Running Lotide database migrations"
	lotide_exec migrate setup
	lotide_exec migrate >/dev/null
	eend $?
}

lotide_exec() {
	start-stop-daemon --exec "$command" --user "$command_user" \
		-- $command_args $*
}
